<script setup>
import { fetchOperatorList, postDeleteOperator, postResetPassword } from '@/api/operator'
import { fetchRoleList } from '@/api/roleApi'
import { onMounted, ref, computed } from 'vue'
import AddOperator from './components/AddOperator.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'

// 对话框可见状态
const dialogVisible = ref(false)

// 当前编辑的操作人员ID
const currentOperatorId = ref(null)

// 添加操作人员组件引用
const addOperatorRef = ref(null)

// 角色列表
const roleList = ref([])

// 角色ID到名称的映射
const roleMap = computed(() => {
  const map = {}
  roleList.value.forEach((role) => {
    map[role.dealerRoleId] = role.roleName
  })
  return map
})

// 打开添加操作人员对话框
const openAddOperatorDialog = () => {
  currentOperatorId.value = null
  dialogVisible.value = true
}

// 打开编辑操作人员对话框
const openEditOperatorDialog = (row) => {
  currentOperatorId.value = row.dealerOperatorId
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  // 延迟重置表单，确保动画完成后再重置
  setTimeout(() => {
    if (addOperatorRef.value) {
      addOperatorRef.value.resetForm()
    }
  }, 300)
}

// 操作人员列表数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await fetchRoleList()
    if (res.success) {
      roleList.value = res.data || []
    }
  } catch (error) {
    logger.error('获取角色列表失败', error)
  }
}

// 获取操作人员列表
const fetchOperatorData = async () => {
  try {
    loading.value = true
    const res = await fetchOperatorList()
    if (res.success) {
      tableData.value = res.data || []
    } else {
      tableData.value = []
      ElMessage.error(res.msg || '获取操作人员列表失败')
    }
  } catch (error) {
    logger.error('获取操作人员列表失败', error)
    ElMessage.error('获取操作人员列表失败')
  } finally {
    loading.value = false
  }
}

// 删除操作人员
const handleDeleteOperator = async (row) => {
  try {
    loading.value = true
    const res = await postDeleteOperator(row.dealerOperatorId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await fetchOperatorData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    logger.error('删除操作人员失败', error)
    ElMessage.error('删除操作人员失败')
  } finally {
    loading.value = false
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const res = await postResetPassword(row.dealerOperatorId)
    if (res.code === 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg || '重置密码失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('重置密码失败', error)
      ElMessage.error('重置密码失败')
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([fetchOperatorData(), fetchRoles()])
})
</script>

<template>
  <!-- 使用单个对话框，根据currentOperatorId判断是添加还是编辑 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentOperatorId ? '编辑操作人员' : '添加操作人员'"
    width="700"
    destroy-on-close
    align-center
  >
    <AddOperator
      ref="addOperatorRef"
      :dealer-operator-id="currentOperatorId"
      @success="fetchOperatorData"
      @close="closeDialog"
    />
  </el-dialog>

  <div class="s-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-button type="primary" @click="openAddOperatorDialog">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          添加操作人员
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="loginCode" label="账号" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="phoneNumber" label="手机号" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag type="success" v-if="roleMap[row.dealerRoleId]">{{
              roleMap[row.dealerRoleId]
            }}</el-tag>
            <el-tag type="warning" v-else>超级管理员</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.operatorEnabled ? 'success' : 'danger'">
              {{ row.operatorEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditOperatorDialog(row)">
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>

            <el-button type="warning" size="small" @click="handleResetPassword(row)">
              <template #icon>
                <el-icon><LineMdSecurityTwotone /></el-icon>
              </template>
              重置密码
            </el-button>

            <el-popconfirm
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除操作人员 '${row.nickname}' 吗？`"
              width="250"
              confirm-button-type="danger"
              @confirm="handleDeleteOperator(row)"
              :disabled="row.category === 1"
            >
              <template #reference>
                <el-tooltip v-if="row.category === 1" content="超级管理员无法删除" placement="top">
                  <el-button type="danger" size="small" :disabled="true">
                    <template #icon>
                      <el-icon><LineMdTrash /></el-icon>
                    </template>
                    删除
                  </el-button>
                </el-tooltip>
                <el-button v-else type="danger" size="small" :disabled="false">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.s-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    padding: 10px;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;

    .el-table {
      flex: 1;
    }
  }
}
</style>
